import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputvalue: '',
    nextId: 5,
    viewKey: 'all'
  },
  mutations: {
    initList(state, list) {
      state.list = list
    },
    InputChange(state, val) {
      state.inputvalue = val
      // console.log(state.inputvalue);
    },
    AddItem(state) {
      const obj = {
        // id: state.list.length,
        id: state.nextId,
        info: state.inputvalue.trim(),
        done: false
      }
      state.list.push(obj)
      state.nextId +=1 ;
      state.inputvalue = ''
    },
    removeItem(state, id) {
      const i = state.list.findIndex(x => x.id === id)
      if (i !== -1) {
        state.list.splice(i, 1)
      }
    },
    stateChange(state, newState) {
      const i = state.list.findIndex(x => x.id == newState.id)
      if (i != -1) {
        state.list[i].done = newState.status
      }
    },
    cleanDone(state) {
      state.list = state.list.filter(x => x.done === false)
    },
    ChangeList(state, key) {
      state.viewKey = key
    }
  },
  actions: {
    getList(context) {
      axios.get('../list.json').then(({ data }) => {
        context.commit('initList', data)
      })
    }
  },
  getters: {
    unDoneLength(state) {
      return state.list.filter(x => x.done === false).length
    },
    infolist(state){
      if(state.viewKey ==='all'){
        return state.list
      }
      if(state.viewKey ==='undone'){
        return state.list.filter(x => x.done === false)
      }
      if(state.viewKey ==='done'){
        return state.list.filter(x => x.done === true)
      }
      return state.list
    }
  },
  modules: {
  }
})
